<?php

namespace console\controllers;

use Carbon\Carbon;
use common\models\db\Log;
use QL\QueryList;
use common\Tools;
use yii\console\Controller;
use yii\helpers\FileHelper;

class JobController extends Controller
{
    /**
     * php yii job/check
     * @desc 检测计划任务是否执行
     */
    public function actionCheck()
    {
        Tools::yiiLog(Carbon::now()->toDateTimeString(), "check-schedule");
    }

    /**
     * php yii job/yiichina-sign
     * @desc https://www.yiichina.com 签到
     * @throws
     */
    public function actionYiichinaSign()
    {
        $ql = QueryList::getInstance();
        $ql->get("https://www.yiichina.com/login");
        $csrf = $ql->find("input[name='_csrf']")->val();
        $username = \Yii::$app->params['yiichina-username'];
        $password = \Yii::$app->params['yiichina-password'];;
        $userInfo= [
            '_csrf'  => $csrf,
            'LoginForm[username]'  => $username,
            'LoginForm[password]'  => $password,
            'LoginForm[rememberMe]'  => '1',
        ];
        $ql->post("https://www.yiichina.com/login", $userInfo);
        $ql->get("https://www.yiichina.com");
        $csrf = $ql->find("input[name='_csrf']")->val();
        $ql->post("https://www.yiichina.com/ajax/registration", [
            '_csrf'  => $csrf,
        ], [
            'headers' => [
                'accept' => "application/json, text/javascript, */*; q=0.01",
                'accept-encoding' => "gzip, deflate, br",
                'accept-language' => "en,zh-CN;q=0.9,zh;q=0.8,zh-TW;q=0.7",
                'content-type' => "application/x-www-form-urlencoded; charset=UTF-8",
                'origin' => "https://php.la",
                'referer' => "https://php.la",
                'user-agent' => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
                'x-csrf-token' => $csrf,
                'x-requested-with' => "XMLHttpRequest",
            ],
        ]);
        var_dump($ql->getHtml());
    }

    /**
     * php yii job/php-la-sign
     * @desc https://php.la/ 签到
     * @throws
     */
    public function actionPhpLaSign()
    {
//        $home_url = "https://phpqz.com";
        $home_url = "https://q.yiichina.com";
        $ql = QueryList::getInstance();
        $ql->get("{$home_url}/login");
        $csrf = $ql->find("input[name='_csrf-frontend']")->val();
        $username = \Yii::$app->params['yiichina-username'];;
        $password = \Yii::$app->params['yiichina-password'];;
        $userInfo= [
            '_csrf-frontend'  => $csrf,
            'LoginForm[username]'  => $username,
            'LoginForm[password]'  => $password,
            'LoginForm[rememberMe]'  => '1',
        ];
        $ql->post("{$home_url}/login", $userInfo);
        $ql->get("{$home_url}");
        $csrf_token = $ql->find('meta[name="csrf-token"]')->attr('content');
        $ql->post("{$home_url}/registration", [
            '_csrf'  => $csrf_token,
        ], [
            'headers' => [
                'accept' => "application/json, text/javascript, */*; q=0.01",
                'accept-encoding' => "gzip, deflate, br",
                'accept-language' => "en,zh-CN;q=0.9,zh;q=0.8,zh-TW;q=0.7",
                'content-type' => "application/x-www-form-urlencoded; charset=UTF-8",
                'origin' => "{$home_url}",
                'referer' => "{$home_url}",
                'user-agent' => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
                'x-csrf-token' => $csrf_token,
                'x-requested-with' => "XMLHttpRequest",
            ],
        ]);
        var_dump($ql->getHtml());
    }

    /**
     * php yii job/tig2-sign
     * @desc https://tig2.eu.org/ 签到
     * @throws
     */
    public function actionTig2Sign()
    {
        $domain = "tig2.eu.org";
        $this->_tig2sign($domain);
    }

    /**
     * php yii job/tig2-backup-sign
     * @desc https://tig2.eu.org/ 签到
     * @throws
     */
    public function actionTig2BackupSign()
    {
        $domain = "tig2.japaneast.cloudapp.azure.com";
        $this->_tig2sign($domain);
    }

    private function _tig2sign($domain)
    {
        $baseUri = "Https://".$domain;
        $ql = QueryList::getInstance();
        $username = \Yii::$app->params['tig2-username'];
        $password = \Yii::$app->params['tig2-password'];
        $userInfo= [
            'username'  => $username,
            'password'  => $password,
        ];
        $ql->get("{$baseUri}/login");
        $loginHtml = $ql->getHtml();
        preg_match('/\"csrf_token\"\:\"([\w\-\_]+)\"/', $loginHtml, $matches);
//        preg_match('/\"csrf_token\"\:\"/', $loginHtml, $matches);
        $csrfToken = $matches[1];
        $ql->post("{$baseUri}/login", $userInfo, [
            'headers' => [
                'ority' => $domain,
//                ':method' => 'POST',
//                ':path' => '/login',
//                ':scheme' => 'https',
                'accept' => '*/*',
                'accept-encoding' => 'gzip, deflate, br',
                'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                'cache-control' => 'no-cache',
                'content-length' => '33',
                'content-type' => 'application/x-www-form-urlencoded; charset=UTF-8',
//                'cookie' => 'express.sid=s%3AcU3j6HaUN4r12Ph8MPi4xQlR3oAF1LQc.v6r4EXpUmD8r1urykwvhFsSMkKRi%2B5MqQtY5DIQtn28',
                'origin' => 'https://tig2.eu.org',
                'pragma' => 'no-cache',
                'sec-ch-ua' => '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
                'sec-ch-ua-mobile' => '?0',
                'sec-ch-ua-platform' => '"Windows"',
                'sec-fetch-dest' => 'empty',
                'sec-fetch-mode' => 'cors',
                'sec-fetch-site' => 'same-origin',
                'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42',
                'x-csrf-token' => $csrfToken,
                'x-requested-with' => 'XMLHttpRequest',
            ],
        ]);
        $ql->get($baseUri);
        $homeHtml = $ql->getHtml();
        preg_match('/\"csrf_token\"\:\"([\w\-\_]+)\"/', $homeHtml, $matches);
        $csrfToken = $matches[1];
        var_dump($csrfToken);
        $ql->get("{$baseUri}/checkin", [
            '_' => time()."000",
        ], [
            'headers' => [
                'Accept' => '*/*',
                'Accept-Encoding' => 'gzip, deflate, br',
                'Accept-Language' => 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
                'Connection' => 'keep-alive',
                'Host' => 'tig2.eu.org',
                'Sec-Fetch-Dest' => 'empty',
                'Sec-Fetch-Mode' => 'cors',
                'Sec-Fetch-Site' => 'same-origin',
                'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0',
                'X-Requested-With' => 'XMLHttpRequest',
                'X-Return-To' => '/user/bnsdmm/settings',
            ],
        ]);
        var_dump($ql->getHtml());
    }

    /**
     * 日志清理超出365天的
     * php yii job/log-clear
     * @param int $keep
     */
    public function actionLogClear($keep = 86400 * 365)
    {
        Log::deleteAll(['<', 'log_time', Carbon::now()->timestamp - $keep]);
    }

    /**
     * 清空日志表
     * php yii job/db-log-clear-all
     */
    public function actionDbLogClearAll()
    {
        Log::deleteAll();
    }

    /**
     * 生成 xunsearch ini 文件
     * php yii job/generate-xunsearch-ini-files
     * @return void
     */
    public function actionGenerateXunsearchIniFiles()
    {
        \Yii::$app->xunsearch->generateIniFiles();
    }

    /**
     * 备份配置文件
     * php yii job/config-files-backup
     * @return void
     * @throws \yii\base\Exception
     */
    public function actionConfigFilesBackup()
    {
        $configFiles = [
            '@common/config/bootstrap-local.php',
            '@common/config/main-local.php',
            '@console/schedule.php',
        ];
        $backupBaseDir = '@storage_root/config-backup';
        $backupBaseDir = \Yii::getAlias($backupBaseDir);
        if (!is_dir($backupBaseDir)) {
            FileHelper::createDirectory($backupBaseDir);
        }
        $md5Files = [];
        foreach ($configFiles as $k => $v) {
            $configFile = \Yii::getAlias($v);
            $md5File = md5_file($configFile);
            $md5Files[] = $md5File;
        }
        $md5 = md5(implode('-', $md5Files));
        $backupDir = $backupBaseDir.'/'.$md5;
        if (!is_dir($backupDir)) {
            FileHelper::createDirectory($backupDir);
            $backupHasDateDir = $backupDir.'/'.date('Ymd');
            foreach ($configFiles as $k => $v) {
                $configFile = \Yii::getAlias($v);
                $backupFile = $backupHasDateDir.str_replace('@', '/', $v);
                if (!is_dir(dirname($backupFile))) {
                    FileHelper::createDirectory(dirname($backupFile));
                }
                copy($configFile, $backupFile);
            }
        }
    }
}